package com.dsj.dao;

import com.dsj.entity.OrderItemEntity;
import com.dsj.util.DBConnection;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class OrderItemDao {
    private Connection connection = null;  // 数据库连接对象
    private PreparedStatement ps = null;  // 预处理语句对象
    private DBConnection jdbc = null;  // 数据库连接工具对象
    public OrderItemDao() {
        jdbc = new DBConnection();  // 创建数据库连接对象实例
        connection = jdbc.connetction;  // 获取数据库连接对象的引用
    }

    /**
     * 向数据库中插入订单项
     * @param form 订单项实体类
     * @return 成功返回true，失败返回false
     */
    public boolean insertOrderItem(OrderItemEntity form) {
        String sql = "insert into tb_order_item(order_id,product_id,product_name,product_price,amount) values(?,?,?,?,?)";
        try {
            ps = connection.prepareStatement(sql);
            ps.setString(1, form.getOrderId());
            ps.setInt(2, form.getProductId());
            ps.setString(3, form.getProductName());
            ps.setFloat(4, form.getProductPrice());
            ps.setInt(5, form.getAmount());
            ps.executeUpdate();
            ps.close();
            return true;
        } catch (Exception e) {
            System.out.println("数据库访问失败");
            return false;
        }
    }

    /**
     * 根据订单ID查询订单详情
     * @param orderId 订单ID
     * @return 订单详情列表
     */
    public List<OrderItemEntity> seletOrderDetailById(String orderId) {
        List<OrderItemEntity> list = new ArrayList<>();  // 创建一个空的OrderItemEntity对象的列表
        OrderItemEntity orderDetail = null;  // 创建一个OrderItemEntity对象，初始化为null

        try {
            String sql = "select * from tb_order_item where order_id =?";
            ps = connection.prepareStatement(sql);
            ps.setString(1, orderId);
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                orderDetail = new OrderItemEntity();
                orderDetail.setOrderId(rs.getString("order_id")); // 设置订单ID
                orderDetail.setProductId(rs.getInt("product_id")); // 设置产品ID
                orderDetail.setProductName(rs.getString("product_name")); // 设置产品名称
                orderDetail.setProductPrice(rs.getFloat("product_price")); // 设置产品价格
                orderDetail.setAmount(rs.getInt("amount")); // 设置数量
                list.add(orderDetail); // 添加到订单详情列表
            }
        } catch (SQLException e) {
            System.out.println("数据库访问失败");
        }
        return list; // 返回订单详情列表
    }

}
